package com.ecar.api.rest.order;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import net.sf.json.JSONObject;

import org.apache.ibatis.metadata.Database;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.ecar.common.annotation.ResponseFilter;
import com.ecar.common.dto.DataBean;
import com.ecar.common.dto.DataBeanEcar;
import com.ecar.common.dto.Pager;
import com.ecar.common.exception.MyException;
import com.ecar.common.util.JSONUtil;
import com.ecar.core.order.entity.Order;
import com.ecar.core.passenger.entity.PaymentComment;
import com.ecar.api.rest.AbstractResource;
import com.ecar.api.service.order.OrderService;
import com.ecar.api.service.order.PaymentCommentService;
import com.ecar.api.support.util.Redis;

/**
 * 类OrderController.java的实现描述：实现订单相关业务处理
 * 
 * @author lbc 2017-9-29 15:02:57
 */
@Controller
@Scope("prototype")
@Path("/order")
public class OrderController extends AbstractResource {

	@Autowired
	OrderService orderService;
	
	@Autowired
	PaymentCommentService paymentCommentService;
	
	@Context
	HttpServletRequest request;

	/**
	 * 司机端我的行程信息(订单列表)
	 * @author yss
	 * @param 
	 */
	@ResponseFilter(target = Order.class, fields = {})
	@GET
	@Path("/{driverId}/myRoute")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean getMyRoute(@PathParam("driverId") String driverId) {
		try {
			Map<String,Object> routeMap=orderService.selectByDriverId(driverId);
			
			return new DataBean(200, routeMap,"我的行程查询成功！");
		} catch (Exception e) {
			log.info("我的行程查询失败: {}", e.getMessage());
			if (e instanceof MyException) {
				return new DataBean(500,new JSONObject(), e.getMessage());
			} else {
				e.printStackTrace();
				return new DataBean(500,new JSONObject(), "我的行程查询失败，服务器异常。");
			}
		}
	}
	
	/**
	 * 所有订单(我的钱包)--为已支付订单
	 * @author yss
	 * @param 
	 */
	@ResponseFilter(target = Order.class, fields = {})
	@GET
	@Path("/{driverId}/allOrder")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean getAllOrder(@PathParam("driverId") String driverId) {
		try {
			List<Order> orderList=orderService.selectAllOrder(driverId);
			
			return new DataBean(200, orderList,"所有订单查询成功！");
		} catch (Exception e) {
			log.info("所有订单查询失败: {}", e.getMessage());
			if (e instanceof MyException) {
				return new DataBean(500,new JSONObject(), e.getMessage());
			} else {
				e.printStackTrace();
				return new DataBean(500,new JSONObject(), "所有订单查询失败，服务器异常。");
			}
		}
	}
	
	/**
	 * 乘客端评论订单
	 * @author fire
	 * @param 
	 */
	@ResponseFilter(target = PaymentComment.class, fields = {})
	@POST
	@Path("/rate")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean rate(JSONObject param) {
		try {
			if (!parse(param) || this.fields == null) return new DataBean(400, new JSONObject(),"请求参数格式错误！");
			if(!this.fields.has("orderNo")||!this.fields.has("rate")){return new DataBean(500,new JSONObject(),"订单号和评论不能为空");}
			log.info("订单{},评论: {}", this.fields.getString("orderNo"),this.fields.toString());
			PaymentComment paymentComment=JSONUtil.deserialize(fields, PaymentComment.class);
			return paymentCommentService.rate(paymentComment);
		} catch (Exception e) {
			log.info("评论失败: {}", e.getMessage());
			if (e instanceof MyException) {
				return new DataBean(500,new JSONObject(), e.getMessage());
			} else {
				e.printStackTrace();
				return new DataBean(500,new JSONObject(), "评论失败，服务器异常。");
			}
		}
	}
	
	/**
	 * 乘客端发送预约订单
	 * @author fire
	 * @param 
	 */
	@POST
	@Path("/send")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean sendOrder(JSONObject param) {
		try {
			if (!parse(param) || this.fields == null) {
				log.info("请求参数格式错误！");
				return new DataBean(400,new JSONObject(),"请求参数格式错误！");
			}
			if(!this.fields.has("orderNum")||!this.fields.has("passengerId")){
				log.info("订单号，乘客ID不能为空");
				return new DataBean(401,new JSONObject(),"订单号，乘客ID不能为空");
			}
			
			String orderNum=this.fields.getString("orderNum");
			int passengerId=this.fields.getInt("passengerId");
			
			String key = Redis.K.ORDER_SEND.to(orderNum);
			int count=0;
			if(Redis.c.exists(key)){
				count=Integer.valueOf(Redis.c.get(key));
			}else{
				//fire
				//添加redis的缓存
				int EXPIRE = 1800;
				Redis.c.setex(Redis.K.ORDER_SEND.to(orderNum), EXPIRE, "1");
			}
			if(count>3){
				orderService.sendNowOrder(orderNum);
				log.info("本单已派送三次,已强制派单");
				return new DataBean(402,new JSONObject(),"本单已派送三次,已强制派单");
			}
			
			Order order=orderService.selectByOrderNum(orderNum);
			if(!order.getPassengerId().equals(passengerId)){
				log.info("订单与乘客不匹配");
				return new DataBean(403,new JSONObject(),"订单与乘客不匹配");
			}
		
			int p = orderService.sendOrder(order);
			if(p==400){
				log.info("订单已有司机接单");
				return new DataBean(405,new JSONObject(),"订单已有司机接单");
			}
			if(p==40){
				log.info("订单状态有误");
				return new DataBean(405,new JSONObject(),"订单状态有误");
			}
			log.info("订单已分发给司机");
		return new DataBean(200,new JSONObject(),"订单已分发给司机");
		} catch (Exception e) {
			log.info("派单失败: {}", e.getMessage());
			e.printStackTrace();
			return new DataBean(500,new JSONObject(),"服务器异常");
		}
	}
	
	/**
	 * 司机端我的行程详情(订单详情)
	 * @author yss
	 * @param 
	 */
//	@ResponseFilter(target = Order.class, fields = {})
//	@GET
//	@Path("/{driverId}/myRouteDetail")
//	@Produces(MediaType.APPLICATION_JSON)
//	public DataBean getMyRouteDetail(@PathParam("driverId") String driverId) {
//		try {
//			Map<String,List<Order>> routeMap=orderService.selectByDriverId(driverId);
//			
//			return new DataBean(200, routeMap,"我的行程查询成功！");
//		} catch (Exception e) {
//			log.info("我的行程查询失败: {}", e.getMessage());
//			if (e instanceof MyException) {
//				return new DataBean(500,new JSONObject(), e.getMessage());
//			} else {
//				e.printStackTrace();
//				return new DataBean(500,new JSONObject(), "我的行程查询失败，服务器异常。");
//			}
//		}
//	}
	
	
	
	/**
	 * 获取订单分页记录
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@GET
	@Path("/rt/{pageNumber}/{pageSize}/page")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBeanEcar pageLogin(
			@PathParam("pageNumber") int pageNumber,
			@PathParam("pageSize") int pageSize) {
		try {
			Pager pager = new Pager();
			HashMap<Object,Object> queryMap = new HashMap();
			if (pageNumber <= 0 || pageSize <= 0)
				return new DataBeanEcar(400, "参数错误。");
			
			parseParams(request);
			if (params != null)
				queryMap = JSONUtil.deserialize(params, HashMap.class);

			if (!params.has("createTime")) {
				queryMap.put("createTime", null);
				queryMap.put("endTime", null);
			}else{
				String[] a = params.getString("createTime").split("#@");
				queryMap.put("createTime", a[0]);
				queryMap.put("endTime", a[1]);
			}
			
			pager.setQueryMap(queryMap);
//			pager.setPageNumber((pageNumber-1)*pageSize);
			queryMap.put("pageNumber", (pageNumber-1)*pageSize);
			queryMap.put("pageSize", pageSize);
//			pager.setPageSize(pageSize);
			return orderService.getByPager(pager);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBeanEcar(500, "查找登录日志列表失败!");
		}
	}

	
	
}
